import React, {Fragment} from 'react';
import Page from 'src/routes/Page';
import {autobind} from 'core-decorators';
import StandardTable from 'src/components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import QueryData from 'src/components/queryData/QueryData';
import OperateModelView from 'src/components/operateModelView/OperateModelView';
import Selector from 'src/components/selector/Selector';
import {Card, Button, Input, message, Icon, InputNumber} from 'antd';
import {connect} from 'dva/index';


@connect(({PlatformDict, loading}) => ({
  PlatformDict,
  loading: loading.models.PlatformDict,
}))
@autobind
class PlatformDict extends Page {
  constructor(props) {
    super(props);
    this.state = {
      paging: {},
      dictResults: [],
      selectedRows: [],
      modifyShow: false,
      formValues: {},
      addShow: false,
      addShowItem: false,
      deleteShow: false,
      shrink: true,
      dictTypes: [],
      queryFromValue: null,
      deleteShowChoose: false,
    };
    this.stateList = [
      {value: 'FORCE_UPDATE', label: '是'},
      {value: 'UN_FORCE_UPDATE', label: '否'},
    ];


  }

  componentDidMount() {
    this.dispatch({
      type: 'PlatformDict/platformDictList',
    });
    this.dispatch({
      type: 'PlatformDict/getDictType',
    })
  }

  shouldComponentUpdate(props, state) {
    let {PlatformDict} = props;

    let {
      platformDictListResult, getDictIdResult, updateDictIdResult, checkDictResult, savePlatformDictResult,
      deleteDictResult, getDictTypeResult, upSortResult, downSortResult
    } = PlatformDict;

    this.rollout(platformDictListResult, false, (result, msg, paging) => {
      this.state.dictResults = result;
      this.state.paging = paging;
      this.state.selectedRows = [];
    }, false);


    this.rollout(getDictIdResult, false, (result, msg, paging) => {
      this.state.formValues = result;
      this.state.modifyShow = true;
    }, false);

    this.rollout(updateDictIdResult, false, (result, msg, paging) => {
      this.state.modifyShow = false;
      this.toast('已修改');
      const {queryFromValue} = this.state;
      this.dispatch({
        type: 'PlatformDict/platformDictList',
        payload: {
          ...queryFromValue,
          current: this.state.paging.current,
          size: this.state.paging.pageSize,
        },
      });
    }, (msg) => {
      this.state.modifyShow = false;
      message.info(msg.message);

    });

    this.rollout(checkDictResult, false, (result, msg, paging) => {
      this.dispatch({
        type: 'PlatformDict/savePlatformDict',
        payload: this.state.formValues,
      });
    }, (msg) => {
    });

    this.rollout(savePlatformDictResult, false, (result, msg, paging) => {
      this.state.addShow = false;
      this.toast('已添加');
      const {queryFromValue} = this.state;
      this.dispatch({
        type: 'PlatformDict/platformDictList',
        payload: {
          ...queryFromValue,
          current: this.state.paging.current,
          size: this.state.paging.pageSize,
        },
      });
    }, (msg) => {
      this.state.addShow = false;
      this.toast(msg.message);
    });

    this.rollout(deleteDictResult, false, (result, msg, paging) => {
      this.state.deleteShow = false;
      this.toast('已删除');
      const {queryFromValue} = this.state;
      this.dispatch({
        type: 'PlatformDict/platformDictList',
        payload: {
          ...queryFromValue,
          current: this.state.paging.current,
          size: this.state.paging.pageSize,
        },
      });
    }, (msg) => {
      this.state.deleteShow = false;
      this.toast(msg.message);
    });

    this.rollout(getDictTypeResult, false, (result, msg, paging) => {
      let list = result.map((item, index) => ({value: item, label: item}));
      this.state.dictTypes = list;
    }, false);

    //上移
    this.rollout(upSortResult, false, (result, msg, paging) => {
      const {queryFromValue} = this.state;
      this.dispatch({
        type: 'PlatformDict/platformDictList',
        payload: {
          ...queryFromValue,
          current: this.state.paging.current,
          size: this.state.paging.pageSize,
        },
      });
    }, (msg) => {
      message.info(msg.message);
    });

    //下移
    this.rollout(downSortResult, false, (result, msg, paging) => {
      const {queryFromValue} = this.state;
      this.dispatch({
        type: 'PlatformDict/platformDictList',
        payload: {
          ...queryFromValue,
          current: this.state.paging.current,
          size: this.state.paging.pageSize,
        },
      });
    }, (msg) => {
      message.info(msg.message);
    });


    return this.equal(props, state);
  }

  render() {
    const {
      paging, dictResults, selectedRows, formValues, modifyShow, addShow, deleteShow, shrink, dictTypes, addShowItem, deleteShowChoose,
    } = this.state;

    // table 显示列表
    const columns = [
      {
        title: '大类', // 列表显示
        dataIndex: 'type', // 数据展示对应字段
      },
      {
        title: '小类',
        dataIndex: 'label',
      },
      {
        title: '值',
        dataIndex: 'value',
        render: (text, record, index) => (
          <p>{record.value.length > 15 ? record.value.substr(0, 15) + '...' : record.value}</p>
        )
      },
      {
        title: '描述',
        dataIndex: 'description',

      },
      {
        title: '强制更新',
        dataIndex: 'enable',
        render: (text, record, index) => (
          <p>{record.enable === 'UN_FORCE_UPDATE' ? '否' : '是'}</p>
        )
      },
      {
        title: '操作',
        render: (text, record, index) => (
          <Fragment>
            <Button type="primary" onClick={() => this.showUpdateView(text, record, index)}>
              修改
            </Button>
            <Button type="primary" style={{marginLeft: '5px'}} onClick={() => this.showAddView(text, record, index)}>
              添加
            </Button>
            <Button type="danger" style={{marginLeft: '5px',}} onClick={() => this.showDeleteView(text, record, index)}>
              删除
            </Button>
          </Fragment>
        ),
      },
    ];

    const formList = [
      {
        label: '大类',
        value: 'type',
        rules: [
          {
            required: true,
            message: '大类不能为空',
          },
        ],
        initialValue: formValues && formValues.type,
        renderItem: <Input placeholder="请输入大类" disabled/>,
      },
      {
        label: '小类',
        value: 'label',
        rules: [],
        initialValue: formValues && formValues.label,
        renderItem: <Input placeholder="请输入小类" disabled/>,
      },
      {
        label: '值',
        value: 'value',
        rules: [],
        initialValue: formValues && formValues.value,
        renderItem: <Input placeholder="请输入输入值"/>,
      },
      {
        label: '排序',
        value: 'sort',
        rules: [],
        initialValue: formValues && formValues.sort,
        renderItem: <InputNumber min={1} defaultValue={500} style={{width: '217px'}}/>,
      },
      {
        label: '强制更新',
        value: 'enable',
        initialValue: formValues && formValues.enable,
        renderItem: (
          <Selector
            placeholder="请选择状态"
            selectList={this.stateList}
            defaultValue={formValues.enable}
          />
        ),
      },
      {
        label: '描述',
        value: 'description',
        initialValue: formValues && formValues.description,
        renderItem: <Input placeholder="请输入描述"/>,
      },
    ];


    const formListAddItem = [
      {
        label: '大类',
        value: 'type',
        rules: [],
        renderItem: <Selector
          placeholder="请选择大类"
          selectList={dictTypes}
        />,
      },
      {
        label: '小类',
        value: 'label',
        rules: [],
        renderItem: <Input placeholder="请输入小类"/>,
      },
      {
        label: '值',
        value: 'value',
        rules: [],
        renderItem: <Input placeholder="请输入输入值"/>,
      },
      {
        label: '排序',
        value: 'sort',
        rules: [],
        renderItem: <InputNumber min={1} defaultValue={500} style={{width: '217px'}}/>,
      },
      {
        label: '强制更新',
        value: 'enable',
        rules: [],
        renderItem: <Selector
          placeholder="请选择状态"
          selectList={this.stateList}
          defaultValue={formValues.enable}
        />,
      },
      {
        label: '描述',
        value: 'description',
        rules: [],
        renderItem: <Input placeholder="请输入描述"/>,
      },

    ];

    const formList1 = [
      {
        label: '小类',
        value: 'label',
        rules: [],
        renderItem: <Input placeholder="请输入小类"/>,
      },
      {
        label: '值',
        value: 'value',
        rules: [],
        renderItem: <Input placeholder="请输入输入值"/>,
      },
      {
        label: '排序',
        value: 'sort',
        rules: [],
        renderItem: <InputNumber min={1} defaultValue={500} style={{width: '217px'}}/>,
      },
    ];
    //放置批量操作的按鈕
    const menu = (
      <span>
         <Button type="danger" style={{marginRight: '10px'}} onClick={this.ondeleteChoose}>
          批量删除
        </Button>
      </span>

    )

    // 渲染按钮内容
    const button = (
      <span>
        <Button type="primary" style={{marginRight: '10px'}} onClick={this.addItem}>
          新增
        </Button>

        <Button type="primary" style={{marginRight: '10px'}} onClick={this.moveUp}>
          <Icon type="arrow-up" theme="outlined" style={{fontWeight: 'bold'}}/>
          上移
        </Button>
        <Button type="primary" style={{marginRight: '10px'}} onClick={this.moveDown}>
        <Icon type="arrow-down" theme="outlined" style={{fontWeight: 'bold'}}/>
          下移
        </Button>

      </span>
    );

    // 查询显示列表
    const searchList = [
      {
        value: 'type',
        renderItem: <Selector placeholder="请选择大类" selectList={dictTypes}/>,
      },
    ];


    return (
      <PageHeaderLayout title="平台字典管理">
        <Card bordered={false}>

          <QueryData
            shrink={shrink}
            queryList={searchList}
            selectedRows={selectedRows}
            onQuery={this.onQuery}
            operateExtra={button}
            menuExtra={menu}

          />

          {/*渲染列表内容*/}
          <StandardTable
            rowShow={true}
            paging={paging}
            selectedRows={selectedRows}
            loading={this.props.loading}
            columns={columns}
            data={dictResults}
            onSelectRow={this._onSelectRow}
            onChange={this._onChange}
          />
        </Card>

        {addShowItem && (
          <OperateModelView
            visible={addShowItem}
            title="新增字典"
            onCancel={() => this.setState({addShowItem: false})}
            formItemList={formListAddItem}
            onSubmit={this.save}
          />
        )}

        {addShow && (
          <OperateModelView
            visible={addShow}
            title="新增字典小类"
            onCancel={() => this.setState({addShow: false})}
            formItemList={formList1}
            formData={formValues}
            onSubmit={this.save}
          />
        )}

        {modifyShow && (
          <OperateModelView
            visible={modifyShow}
            title="修改字典信息"
            onCancel={() => this.setState({modifyShow: false})}
            formItemList={formList}
            formData={formValues}
            onSubmit={this.update}
          />
        )}

        {deleteShow && (
          <OperateModelView
            visible={deleteShow}
            title="删除信息"
            onCancel={() => this.setState({deleteShow: false})}
            operateMode="delete"
            formItemList={formList}
            onOk={() => this.ondelete()}
          />
        )}

        {deleteShowChoose && (
          <OperateModelView
            visible={deleteShowChoose}
            title="删除所选信息"
            onCancel={() => this.setState({deleteShowChoose: false})}
            operateMode="delete"
            onOk={this.chooseDel}
          />
        )}

      </PageHeaderLayout>
    );
  }

  // 行选择
  _onSelectRow(row) {
    this.setState({
      selectedRows: row,
    });
  }

  // 分页 过滤 排序
  _onChange(page, filter, sort) {
    const {queryFromValue} = this.state;
    this.state.selectedRows = [];
    this.dispatch({
      type: 'PlatformDict/platformDictList',
      payload: {
        ...queryFromValue,
        current: page.current,
        size: page.pageSize,
      },
    });
  }

  // 显示新增弹窗
  showAddView(text, record, index) {
    this.setState({formValues: record, addShow: true});
  }

  showDeleteView(text, record, index) {
    this.setState({deleteShow: true, formValues: record});
  }

  // 显示修改弹窗
  // text 为当前行的值
  // record 为当前行数据
  // index 为当前行索引
  showUpdateView(text, record, index) {
    //  获取详情
    this.dispatch({
      type: 'PlatformDict/getDictId',
      payload: record.id,
    });
  }

  // 修改
  update(formValues) {
    this.dispatch({
      type: 'PlatformDict/updateDictId',
      payload: {
        ...formValues
      },
    });
  }

  // 保存
  // formValues 为表单数据
  save(formValues) {
    this.setState({formValues}, () => this.dispatch({
      type: 'PlatformDict/checkDict',
      payload: {
        ...formValues,
      },
    }));

  }

  ondelete() {
    //  删除操作
    let {formValues} = this.state;
    this.dispatch({
      type: 'PlatformDict/deleteDict',
      payload: [formValues.id],
    });

  }

  ondeleteChoose() {
    this.setState({deleteShowChoose: true});
  }

  chooseDel() {
    //批量删除
    let {selectedRows} = this.state;
    let ids = selectedRows.map((item, index) => (item.id));
    this.dispatch({
      type: 'PlatformDict/deleteDict',
      payload: ids,
    });
  }

  addItem() {
    this.setState({formValues: {}, addShowItem: true});
  }

  //  查询方法
  onQuery(formValues) {
    this.setState({queryFromValue: formValues});
    this.dispatch({
      type: 'PlatformDict/platformDictList',
      payload: {
        ...formValues,
      }
    });
  }

  moveUp() {
    let {selectedRows} = this.state;
    if (selectedRows.length === 1) {
      this.dispatch({
        type: 'PlatformDict/upSort',
        payload: selectedRows[0].id,

      });
    } else if (selectedRows.length === 0) {
      message.info('您还未选择要上移的字典!');
    } else {
      message.info('不能选择多项上移！');
    }
  }

  moveDown() {
    let {selectedRows} = this.state;
    if (selectedRows.length === 1) {
      this.dispatch({
        type: 'PlatformDict/downSort',
        payload: selectedRows[0].id,

      });
    } else if (selectedRows.length === 0) {
      message.info('您还未选择要下移的字典!');
    } else {
      message.info('不能选择多项下移！');
    }
  }


}

export default PlatformDict;
